package com.leetcode.LC_MED;

import java.util.ArrayList;
import java.util.List;

public class LC39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        if (candidates.length == 0) {
            return new ArrayList<>();
        }

        ArrayList<List<Integer>> lists = new ArrayList<>();
        backtrack(lists, candidates, 0, target, new ArrayList<>());
        return lists;
    }

    private void backtrack(List<List<Integer>> lists, int[] candidates, int index, int target, List<Integer> list) {
        if (target == 0) {
            lists.add(new ArrayList<>(list));
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            if (candidates[i] <= target) {//限制小数在前，大数在后
                list.add(candidates[i]);
                backtrack(lists, candidates, i, target - candidates[i], list);
                list.remove(list.size() - 1);
            }
        }
    }
}
